<?php

namespace app\admin\controller;

use support\Request;
use think\facade\Db;
use support\View;
use Webman\Event\Event;
use support\exception\ValidateException;
use think\facade\Cache;


class CommonController{
	
	
	
	protected $request = null;
	
	protected $config = null;
	
	
	public function beforeAction(Request $request){
		$this->request = $request;
		
		$app = $this->request->app;
		$controller = $this->request->controller;
		$action = $this->request->action;
		
		$sign_status = session('admin_auth_sign') == data_auth_sign(session('admin'),config('my.password_secrect')) ? true : false;
		
		if(!$sign_status && ($app <> 'admin' || strpos($controller,'Login') === false)){
			return response('<script type="text/javascript">top.parent.frames.location.href="/'.config('app.app_map.admin','admin').'/Login/login";</script>');
        }
		
		$newnodes = [];
		if(session('admin.access')){
			foreach(session('admin.access') as $key=>$val){
				$newnodes[] = str_replace($app,config('app.app_map.'.$app,$app),parse_url($val)['path']);
			}
		}
		
		$white = [];
		if(config('my.nocheck')){
			foreach(config('my.nocheck') as $k=>$v){
				$white[] = str_replace($app,config('app.app_map.'.$app,$app),$v);
			}
		}
		
		$url = $this->request->path();
		if(session('admin.role_id') <> 1 && !in_array($url,$white) && !in_array($action,['getFieldList','getInfo'])){	
			if(!in_array($url,$newnodes)){
				throw new ValidateException("你没有权限访问!");
			}
		}
		
		$config = Cache::get('base_config');
		$this->config = $config;
		
		Event::emit('dolog', session('admin.username'));
		
		View::assign(['base_config' => $config]);
		View::assign(['dialogstate'=>$this->request->get('dialogstate')]);
    }
	
	
	//格式化sql字段查询 转化为 key=>val 结构
	protected function query($sql,$connect='mysql'){
		preg_match_all('/select(.*)from/iUs',$sql,$all);
		if(!empty($all[1][0])){
			$sqlvalue = explode(',',trim($all[1][0]));
		}
		if(strpos($sql,'tkey') !== false){
			$sqlvalue[1] = 'tkey';
		}
		
		if(strpos($sql,'tval') !== false){
			$sqlvalue[0] = 'tval';
		}
		$sql = str_replace('pre_',config('database.connections.'.$connect.'.prefix'),$sql);
		$list = Db::connect($connect)->query($sql);
		$array = [];
		foreach($list as $k=>$v){
			$array[$k]['key'] = $v[$sqlvalue[1]];
			$array[$k]['val'] = $v[$sqlvalue[0]];
			if(isset($sqlvalue[2]) && $sqlvalue[2]){
				$array[$k]['pid'] = $v[$sqlvalue[2]];
			}
		}
		return $array;
	}
	
	
    

}
